<template>
   <!-- 组织架构 -->
   <div class="container">
      <h1>组织架构</h1>
      <div style="height: 20px"></div>
      <el-row
         :gutter="0"
         class="full-height-row"
      >
         <!-- 左侧部门树 -->
         <el-col
            :span="6"
            class="full-height-col"
         >
            <el-card
               class="full-height-card"
               style="overflow-y: scroll"
            >
               <div class="button-container">
                  <el-button
                     type="success"
                     @click="onAddSuperiors"
                     v-if="viewMode === 'basic'"
                     >添加顶级组织</el-button
                  >
               </div>
               <el-tree
                  highlight-current
                  class="full-height-tree"
                  :data="Array.isArray(departmentTree) ? departmentTree : []"
                  node-key="id"
                  :props="treeProps"
                  accordion
                  :default-expanded-keys="[org_id]"
                  :current-node-key="org_id"
                  @node-click="handleNodeClick"
               >
                  <template #default="scope">
                     <div class="custom-tree-node">
                        <span :class="{ 'disabled-node': scope.node.data.status === 0 }">{{ scope.node.label }}</span>
                        <span class="operation-icons">
                           <el-icon
                              @click.stop="handleAddTop(scope.node.data)"
                              class="custom-icon"
                           >
                              <Plus />
                           </el-icon>
                           <el-icon
                              @click.stop="handleEdit(scope.node.data)"
                              class="custom-icon"
                           >
                              <Edit />
                           </el-icon>
                           <br />
                        </span>
                     </div>
                  </template>
               </el-tree>
            </el-card>
         </el-col>
         <!-- 右侧表单 -->
         <el-col
            :span="18"
            class="full-height-col"
         >
            <el-card class="full-height-card">
               <!-- 切换按钮 -->
               <div class="mb-4">
                  <el-radio-group v-model="viewMode">
                     <el-radio-button label="basic">组织详情</el-radio-button>
                     <el-radio-button
                        label="detail"
                        @click="getPositionList"
                        >组织职位</el-radio-button
                     >
                     <el-radio-button
                        label="personnel"
                        @click="getPersonnelList"
                        >组织人员</el-radio-button
                     >
                  </el-radio-group>
               </div>

               <!-- 动态表单 -->
               <el-form
                  :model="formData"
                  label-width="120px"
                  v-if="selectedDepartment"
               >
                  <template v-if="viewMode === 'basic'">
                     <el-form-item label="组织名称:">
                        <el-input
                           v-model="formData.name"
                           disabled
                           style="height: 40px; width: 500px"
                        />
                     </el-form-item>
                     <el-form-item label="组织编号:">
                        <el-input
                           v-model="formData.num"
                           disabled
                           style="height: 40px; width: 500px"
                        />
                     </el-form-item>
                     <el-form-item label="上级组织:">
                        <el-input
                           v-model="formData.parentOrg"
                           disabled
                           style="height: 40px; width: 500px"
                        />
                     </el-form-item>
                     <el-form-item label="组织类型:">
                        <el-input
                           v-model="formData.type"
                           disabled
                           style="height: 40px; width: 500px"
                        />
                     </el-form-item>
                     <el-form-item label="组织主管:">
                        <el-input
                           v-model="formData.manager"
                           disabled
                           style="height: 40px; width: 500px"
                        />
                     </el-form-item>
                     <el-form-item label="描述说明:">
                        <el-input
                           v-model="formData.description"
                           type="textarea"
                           :autosize="{ minRows: 5 }"
                           disabled
                           style="height: 40px; width: 500px"
                        />
                     </el-form-item>
                  </template>
                  <!-- 组织职位 -->
                  <template v-if="viewMode === 'detail'">
                     <!-- 组织职位搜索区域 -->
                     <div class="search-area">
                        <div class="search-item">
                           <label>职位名称：</label>
                           <el-input
                              v-model="positionSearchForm.name"
                              placeholder="输入职位名称"
                              style="width: auto"
                              @keyup.enter="searchPositions"
                           ></el-input>
                        </div>
                        <div class="search-item">
                           <label>职位编号：</label>
                           <el-input
                              v-model="positionSearchForm.code"
                              placeholder="输入职位编号"
                              style="width: auto"
                              @keyup.enter="searchPositions"
                           ></el-input>
                        </div>
                        <div class="search-item">
                           <label>职级：</label>
                           <el-select
                              @change="searchPositions"
                              clearable
                              v-model="positionSearchForm.level"
                              placeholder="请选择职级"
                              style="width: 120px"
                              @keyup.enter="searchPositions"
                           >
                              <el-option
                                 v-for="item in levelList"
                                 :key="item.value"
                                 :label="item.label"
                                 :value="item.value"
                              ></el-option
                           ></el-select>
                        </div>
                        <el-button
                           type="primary"
                           @click="searchPositions"
                           >搜索</el-button
                        >
                        <el-button
                           type="info"
                           @click="resetPositionSearch"
                           >重置</el-button
                        >
                        <el-button
                           type="success"
                           @click="onAddPosition"
                           v-if="viewMode === 'detail'"
                           >添加职位</el-button
                        >
                     </div>
                     <div class="table-wrapper">
                        <div class="table-header">
                           <span class="table-title">职位列表</span>
                           <span class="table-count">共 {{ positionTotal }} 条</span>
                        </div>
                        <el-table
                           :data="positionList || []"
                           style="width: 100%"
                           stripe
                           show-overflow-tooltip
                           v-loading="positionLoading"
                           element-loading-text="加载中..."
                           table-layout="auto"
                        >
                           <el-table-column
                              label="职位名称"
                              prop="position_name"
                              width="auto"
                              show-overflow-tooltip
                           ></el-table-column>
                           <el-table-column
                              label="职级"
                              prop="position_level_name"
                              width="auto"
                           >
                              <template #default="scope">
                                 <p>{{ scope.row.org_position_level.position_level_name }}</p>
                              </template>
                           </el-table-column>
                           <el-table-column
                              label="职位编号"
                              prop="position_num"
                              width="auto"
                           ></el-table-column>
                           <el-table-column
                              min-width="auto"
                              label="描述说明"
                              prop="content"
                              show-overflow-tooltip
                           ></el-table-column>
                           <el-table-column
                              label="状态"
                              width="auto"
                              align="center"
                           >
                              <template #default="scope">
                                 <el-switch
                                    v-model="scope.row.status"
                                    :active-value="1"
                                    :inactive-value="0"
                                    class="ml-2"
                                    @change="handelepositionStatus(scope.row)"
                                 />
                              </template>
                           </el-table-column>
                           <el-table-column
                              label="操作"
                              width="100"
                              align="center"
                              fixed="right"
                           >
                              <template #default="scope">
                                 <el-button
                                    size="small"
                                    type="success"
                                    @click="handleAllocateRoles(scope.row)"
                                 >
                                    编辑
                                 </el-button>
                              </template>
                           </el-table-column>
                           <template #empty>
                              <div class="empty-data">
                                 <el-empty description="暂无职位数据" />
                              </div>
                           </template>
                        </el-table>
                        <!-- 分页组件 -->
                        <!-- 分页 -->
                        <Pagination
                           style="margin: 0"
                           @pageSize="pageSize"
                           @getPage="getPage"
                           :page="positionCurrentPage"
                           :page-size="positionPageSize"
                           :total="positionTotal"
                        />
                     </div>
                  </template>

                  <template v-if="viewMode === 'personnel'">
                     <!-- 组织人员搜索区域 -->
                     <div class="search-area">
                        <div class="search-item">
                           <label>姓名：</label>
                           <el-input
                              v-model="personnelSearchForm.name"
                              placeholder="输入姓名"
                              style="width: 200px"
                              @keyup.enter="searchPersonnel"
                           ></el-input>
                        </div>
                        <div class="search-item">
                           <label>工号：</label>
                           <el-input
                              v-model="personnelSearchForm.workNo"
                              placeholder="输入工号"
                              style="width: 200px"
                              @keyup.enter="searchPersonnel"
                           ></el-input>
                        </div>
                        <div class="search-item">
                           <label>职位：</label>
                           <el-select
                              v-model="personnelSearchForm.position"
                              placeholder="请选择"
                              style="width: 200px"
                              clearable
                           >
                              <el-option
                                 label="请选择"
                                 value=""
                              ></el-option>
                              <el-option
                                 v-for="item in positionList"
                                 :key="item.id"
                                 :label="item.position_name"
                                 :value="item.id"
                              ></el-option>
                           </el-select>
                        </div>
                        <div class="search-item">
                           <label>在职状态：</label>
                           <el-select
                              v-model="personnelSearchForm.job_status"
                              placeholder="请选择"
                              style="width: 200px"
                              clearable
                           >
                              <el-option
                                 v-for="item in jobStatus"
                                 :key="item.value"
                                 :label="item.label"
                                 :value="item.value"
                              ></el-option>
                           </el-select>
                        </div>
                        <el-button
                           type="primary"
                           @click="searchPersonnel"
                           >搜索</el-button
                        >
                        <el-button
                           type="info"
                           @click="resetPersonnelSearch"
                           >重置</el-button
                        >
                     </div>
                     <div class="personnel-actions">
                        <el-button
                           type="success"
                           @click="addPersonnel"
                           >添加人员</el-button
                        >
                     </div>
                     <div class="table-wrapper">
                        <div class="table-header">
                           <span class="table-title">人员列表</span>
                           <span class="table-count">共 {{ personnelTotal }} 条</span>
                        </div>
                        <el-table
                           :data="personnelList || []"
                           style="width: 100%"
                           stripe
                           show-overflow-tooltip
                           v-loading="personnelLoading"
                           element-loading-text="加载中..."
                           table-layout="auto"
                        >
                           <el-table-column
                              label="姓名"
                              prop="name"
                              width="100"
                           ></el-table-column>
                           <el-table-column
                              label="工号"
                              prop="num"
                              width="100"
                           ></el-table-column>
                           <el-table-column
                              label="职位"
                              prop="position_name"
                              min-width="150"
                              show-overflow-tooltip
                           >
                        <template #default="scope">{{ scope.row.org_position.position_name }}</template>
                        </el-table-column>
                           <el-table-column
                              label="操作人"
                              prop="admin_name"
                              min-width="100"
                           ></el-table-column>
                           <el-table-column
                              label="操作时间"
                              prop="updated_at"
                              min-width="150"
                           ></el-table-column>
                           <el-table-column
                              label="在职状态"
                              width="100"
                              align="center"
                           >
                              <template #default="scope">
                                 <el-switch
                                    v-model="scope.row.job_status"
                                    :active-value="1"
                                    :inactive-value="2"
                                    class="ml-2"
                                    @change="handleStatusChange(scope.row)"
                                 />
                              </template>
                           </el-table-column>
                           <el-table-column
                              label="操作"
                              width="100"
                              align="center"
                              fixed="right"
                           >
                              <template #default="scope">
                                 <el-button
                                    size="small"
                                    type="success"
                                    @click="editPersonnel(scope.row)"
                                 >
                                    编辑
                                 </el-button>
                              </template>
                           </el-table-column>
                           <template #empty>
                              <div class="empty-data">
                                 <el-empty description="暂无人员数据" />
                              </div>
                           </template>
                        </el-table>

                        <!-- 分页 -->
                        <Pagination
                           style="margin: 0"
                           @pageSize="pageSize"
                           @getPage="getPage"
                           :page="personnelCurrentPage"
                           :page-size="personnelPageSize"
                           :total="personnelTotal"
                        />
                     </div>
                  </template>
               </el-form>

               <div
                  v-else
                  class="empty-tip"
               >
                  请选择左侧部门查看详细信息
               </div>
            </el-card>
         </el-col>
      </el-row>
   </div>
   <AuthorityAdd
      @init="init"
      ref="authorityAddRef"
   />
   <!-- 分配角色 -->
   <allocateRoles ref="allocateRolesRef"></allocateRoles>
   <!-- 组织操作 -->
   <AuthorityAction
      @refresh="getOrgList"
      ref="authorityActionRef"
   ></AuthorityAction>
   <!-- 添加人员 -->
   <AddPersonnel
      ref="addPersonnelRef"
      @refresh="getPersonnelList"
   ></AddPersonnel>
   <!-- 添加职位 -->
   <AddPosition
      @refresh="getPositionList"
      :tissueList="Array.isArray(departmentTree) ? departmentTree : []"
      :selectedNodeId="selectedNodeId"
      ref="addPositionRef"
   ></AddPosition>
</template>

<script setup>
   import { ref, reactive, onMounted, watch } from "vue";
   import { Plus, Edit, Delete } from "@element-plus/icons-vue";
   import { ElMessageBox, ElMessage } from "element-plus";
   import AuthorityAdd from "./authorityAdd/authorityAdd.vue";
   import allocateRoles from "./authorityAdd/allocateRoles.vue";
   import AuthorityAction from "./authorityAdd/authorityAction.vue";
   import AddPersonnel from "./AddPersonnel/AddPersonnel.vue";
   import AddPosition from "./authorityAdd/addPosition.vue";
   import Pagination from "@/components/Pagination.vue";
   import api from "@/api/index.js";
   const showBackButton = false; // 更改为 `false` 表示不需要返回按钮
   const addPositionRef = ref(null); // 添加职位弹窗
   const pageTitle = "组织列表"; // 更改为你需要的标题
   const authorityAddRef = ref(null); // 组织新增
   const allocateRolesRef = ref(null); // 分配角色
   const authorityActionRef = ref(null); // 组织操作
   const addPersonnelRef = ref(null); // 添加人员
   const positionList = ref([]); // 职位列表
   const personnelList = ref([]); // 人员列表
   let org_id = ref(null); // 组织id
   // 模拟部门数据
   const departmentTree = ref([]);

   // 监听 org_id 的变化
   watch(
      () => org_id.value,
      (newVal) => {
         if (newVal) {
            getPersonnelList();
         }
      }
   );

   // 组织职位搜索表单
   const positionSearchForm = reactive({
      name: "",
      code: "",
      level: "",
   });

   // 组织人员搜索表单
   const personnelSearchForm = reactive({
      name: "",
      workNo: "",
      position: "",
      job_status: 1,
   });
   const jobStatus = ref([
      {
         label: "在职",
         value: 1,
      },
      {
         label: "离职",
         value: 2,
      },
   ]);
   let levelList = ref([]);
   // 获取职级列表
   const getLevelList = async () => {
      try {
         const res = await api.authority.getLevelList();
         if (res.code == 200) {
            // 检查 res.data 是否为数组
            if (Array.isArray(res.data.data)) {
               levelList.value = res.data.data.map((item) => ({
                  label: item.position_level_name,
                  value: String(item.id), // 确保ID为字符串类型
               }));
               console.log("职级列表获取成功", levelList.value);
            } else {
               // 如果 res.data.data 不是数组，可能是对象或其他格式
               console.error("获取职级列表数据格式错误:", res.data);
               levelList.value = []; // 设置为空数组
            }
         } else {
            console.error("获取职级列表失败:", res.msg);
            ElMessage.error(res.msg || "获取职级列表失败");
            levelList.value = []; // 设置为空数组
         }
      } catch (error) {
         console.error("获取职级列表出错:", error);
         ElMessage.error("获取职级列表出错，请重试");
         levelList.value = []; // 设置为空数组
      }
   };
   // 职位分页
   const positionCurrentPage = ref(1);
   const positionPageSize = ref(5);
   const positionTotal = ref(30);
   // 组织人员分页
   const personnelCurrentPage = ref(1);
   const personnelPageSize = ref(5);
   const personnelTotal = ref(30);

   // 添加加载状态标志
   const positionLoading = ref(false);
   const personnelLoading = ref(false);
   // 获取组织列表
   const getOrgList = async () => {
      const res = await api.authority.getOrgList();
      if (res.code === 200) {
         org_id.value = res.data[0].id;
         getOrgDetail({ id: org_id.value });
         // 确保数据是数组格式
         if (Array.isArray(res.data)) {
            departmentTree.value = res.data;
            console.log("departmentTree", departmentTree.value);
         } else {
            console.error("获取组织列表数据格式错误，期望数组格式", res.data);
            departmentTree.value = []; // 设置为空数组
            ElMessage.error("组织列表数据格式错误");
         }
      } else {
         ElMessage.error(res.msg);
         departmentTree.value = []; // 设置为空数组
      }
   };

   // 获取职位列表
   const getPositionList = async () => {
      if (!org_id.value) {
         ElMessage.warning("请先选择组织");
         return;
      }

      positionLoading.value = true;

      const params = {
         org_id: org_id.value, // 组织id
         position_name: positionSearchForm.name || "", // 职位名称
         position_num: positionSearchForm.code || "", // 职位编号
         position_level_id: positionSearchForm.level || "", // 职级编号
         pageSize: String(positionPageSize.value),
         page: String(positionCurrentPage.value),
      };
      let _p = removeEmpty(params);
      try {
         const res = await api.authority.getPositionList(_p);
         if (res.code === 200) {
            positionList.value = Array.isArray(res.data.data) ? res.data.data : [];
            console.log("职位列表", positionList.value);
            positionTotal.value = res.data.total || 0;
         } else {
            ElMessage.error(res.msg || "获取职位列表失败");
            positionList.value = [];
            positionTotal.value = 0;
         }
      } catch (error) {
         console.error("获取职位列表失败", error);
         ElMessage.error("获取职位列表失败，请稍后再试");
         positionList.value = [];
         positionTotal.value = 0;
      } finally {
         positionLoading.value = false;
      }
   };
   // 组织状态切换
   const onPression = async (row) => {
      let originalStatus = row.status;
      try {
         const res = await api.authority.editOrganization({
            id: row.id,
            status: row.status == 1 ? 0 : 1,
         });
         if (res.code === 200) {
            ElMessage.success("组织状态切换成功");
            getOrgList();
         } else {
            ElMessage.error(res.msg || "组织状态切换失败");
         }
      } catch (error) {
         row.status = originalStatus;
         ElMessage.error("组织状态切换失败，请稍后再试");
      }
   };
   // 获取人员列表
   const getPersonnelList = async () => {
      if (!org_id.value) {
         ElMessage.warning("请先选择组织");
         return;
      }
      // 点击人员的时候就要立马获取职位列表
      getPositionList();
      personnelLoading.value = true;

      const params = {
         org_id: org_id.value, // 组织id
         name: personnelSearchForm.name || "", // 姓名
         num: personnelSearchForm.workNo || "", // 工号
         position_id: personnelSearchForm.position || "", // 职位
         job_status: personnelSearchForm.job_status || "", // 在职状态 - 直接使用下拉框的值
         pageSize: String(personnelPageSize.value),
         page: String(personnelCurrentPage.value),
      };
      let _p = removeEmpty(params);
      try {
         const res = await api.authority.getPersonnelList(_p);
         if (res.code === 200) {
            // 检查返回的数据格式并适当处理
            if (Array.isArray(res.data)) {
               personnelList.value = res.data;
               personnelTotal.value = res.data.length || 0;
            } else if (res.data && res.data.data) {
               personnelList.value = res.data.data;
               personnelTotal.value = res.data.total || 0;
            } else {
               personnelList.value = [];
               personnelTotal.value = 0;
            }
         } else {
            ElMessage.error(res.msg || "获取人员列表失败");
            personnelList.value = [];
            personnelTotal.value = 0;
         }
      } catch (error) {
         console.error("获取人员列表失败", error);
         ElMessage.error("获取人员列表失败，请稍后再试");
         personnelList.value = [];
         personnelTotal.value = 0;
      } finally {
         personnelLoading.value = false;
      }
   };
   // 职位状态切换
   const handelepositionStatus = async (row) => {
      let originalStatus = row.status;
      try {
         // 创建API参数
         let params = {
            id: row.id,
            status: row.status, // 使用当前已切换后的状态
         };

         const res = await api.authority.editorialPosition(params);
         if (res.code === 200) {
            ElMessage.success("职位状态更新成功");
            // 刷新列表以获取最新数据
            getPositionList();
         } else {
            // API调用失败，恢复UI状态并显示错误
            row.status = originalStatus;
            ElMessage.error(res.msg || "职位状态更新失败");
         }
      } catch (error) {
         ElMessage.error("职位状态更新失败，请稍后再试");
      }
   };
   // 人员状态切换
   const handleStatusChange = async (row) => {
      let originalStatus = row.job_status;

      try {
         // 创建API参数
         let params = {
            id: row.id,
            job_status: row.job_status, // 使用当前已切换后的状态
         };

         const res = await api.authority.editPosition(params);
         if (res.code === 200) {
            ElMessage.success("人员状态更新成功");
            // 刷新列表以获取最新数据
            getPersonnelList();
         } else {
            // API调用失败，恢复UI状态并显示错误
            row.job_status = originalStatus;
            ElMessage.error(res.msg || "人员状态更新失败");
         }
      } catch (error) {
         // 网络错误等异常情况，恢复UI状态
         row.job_status = originalStatus;
         console.error("人员状态更新失败", error);
         ElMessage.error("人员状态更新失败，请稍后再试");
      }
   };

   const treeProps = {
      children: "children",
      label: "name",
   };

   const viewMode = ref("basic");
   const selectedDepartment = ref(1);
   const formData = reactive({
      name: "",
      manager_name: "",
      role: "",
      parentOrg: "",
      type: "",
      description: "",
      num: "",
   });

   // 职位搜索
   const searchPositions = () => {
      // positionCurrentPage.value = 1; // 重置到第一页
      getPositionList();
   };

   // 重置职位搜索
   const resetPositionSearch = () => {
      // 重置搜索表单
      Object.keys(positionSearchForm).forEach((key) => {
         positionSearchForm[key] = "";
      });
      positionCurrentPage.value = 1; // 重置到第一页
      getPositionList(); // 刷新列表
   };

   // 设置每页显示条数
   const pageSize = (value) => {
      if (viewMode.value === "detail") {
         positionPageSize.value = value;
         getPositionList();
      } else if (viewMode.value === "personnel") {
         personnelPageSize.value = value;
         getPersonnelList();
      }
   };

   // 获取当前页码
   const getPage = (value) => {
      if (viewMode.value === "detail") {
         positionCurrentPage.value = value;
         getPositionList();
      } else if (viewMode.value === "personnel") {
         personnelCurrentPage.value = value;
         getPersonnelList();
      }
   };

   // 人员搜索
   const searchPersonnel = () => {
      // personnelCurrentPage.value = 1; // 重置到第一页
      getPersonnelList();
   };

   // 重置人员搜索
   const resetPersonnelSearch = () => {
      // 重置搜索表单
      Object.keys(personnelSearchForm).forEach((key) => {
         personnelSearchForm[key] = "";
      });
      // personnelCurrentPage.value = 1; // 重置到第一页
      getPersonnelList(); // 刷新列表
   };

   // 添加人员
   const addPersonnel = () => {
      if (!org_id.value) {
         ElMessage.warning("请先选择一个组织");
         return;
      }
      addPersonnelRef.value.openDialog({
         org_id: org_id.value, // 预设当前选中的组织
      });
   };

   // 编辑人员
   const editPersonnel = (row) => {
      if (!row || !row.id) {
         ElMessage.warning("无效的人员数据");
         return;
      }
      // 编辑人员逻辑
      addPersonnelRef.value.openDialog(row);
   };

   // 人员分页事件
   const handlePersonnelSizeChange = (size) => {
      personnelPageSize.value = size;
      // 重新加载数据
   };

   const handlePersonnelCurrentChange = (page) => {
      personnelCurrentPage.value = page;
      // 重新加载数据
   };
   // 去除空值
   const removeEmpty = (obj) => {
      let _O = Object.keys(obj).reduce((acc, key) => {
         if (obj[key] !== "" && obj[key] !== null && obj[key] !== undefined) {
            acc[key] = obj[key];
         }
         return acc;
      }, {});
      return _O;
   };
   // 添加职位
   const onAddPosition = () => {
      if (!org_id.value) {
         ElMessage.warning("请先选择一个组织");
         return;
      }
      addPositionRef.value.openDialog();
   };
   const selectedNodeId = ref(""); // 选中的节点id

   //      const res = await api.authority.getOrgDetail({ id: nodeData.id });
   const getOrgDetail = async (nodeData) => {
      const res = await api.authority.getOrgDetail({ id: nodeData.id });
      if (res.code === 200) {
         org_id.value = nodeData.id ? nodeData.id : departmentTree.value[0].id;
         // 将点击的部门数据赋值给selectedDepartment
         selectedDepartment.value = nodeData;
         // 将点击的部门数据赋值给formData
         Object.assign(formData, {
            name: nodeData.name, // 组织名称
            manager: nodeData.manager_name || "-", // 组织主管
            parentOrg: res.data.parent_name || "-", // 上级组织
            type: nodeData.type == 1 ? "部门" : "公司", // 组织类型
            description: res.data.content || "-", // 描述说明
            num: res.data.num || "-", // 组织编号
         });
      }
   };
   // 点击部门树节点的数据信息
   const handleNodeClick = async (nodeData) => {
      selectedNodeId.value = nodeData.id;
      getOrgDetail(nodeData);
      // 根据当前视图模式加载相应数据
      if (viewMode.value === "detail") {
         // 重置职位搜索表单和分页
         Object.keys(positionSearchForm).forEach((key) => {
            positionSearchForm[key] = "";
         });
         positionCurrentPage.value = 1;
         personnelSearchForm.job_status = 1;
         getPositionList();
      } else if (viewMode.value === "personnel") {
         // 重置人员搜索表单和分页
         Object.keys(personnelSearchForm).forEach((key) => {
            personnelSearchForm[key] = "";
         });
         personnelCurrentPage.value = 1;
         personnelSearchForm.job_status = 1;
         getPersonnelList();
      }
   };

   // // 添加顶级组织
   const onAddSuperiors = () => {
      authorityActionRef.value.handleDialog();
   };

   // 添加组织
   const handleAddTop = (data) => {
      authorityAddRef.value.handleDialog(data, "add");
   };

   // 编辑组织
   const handleEdit = (data) => {
      authorityAddRef.value.handleDialog(data, "edit");
   };

   // 编辑组织职位
   const handleAllocateRoles = (row) => {
      addPositionRef.value.openDialog(row);
   };

   // 删除组织
   const handleDelete = (data) => {
      ElMessageBox.confirm("确定要删除该组织吗？", "提示", {
         confirmButtonText: "确定",
         cancelButtonText: "取消",
         type: "warning",
      })
         .then(() => {
            // 这里添加删除接口调用
            ElMessage.success("删除成功");
         })
         .catch(() => {});
   };

   // 初始化方法
   const init = () => {
      getOrgList();
   };

   // 分配角色按钮点击事件
   const onAssignRoles = () => {
      allocateRolesRef.value.handleDialog();
   };

   // 添加监听viewMode变化的代码
   watch(viewMode, (newValue) => {
      if (org_id.value) {
         if (newValue === "detail") {
            getPositionList();
         } else if (newValue === "personnel") {
            getPersonnelList();
         }
      }
   });

   // 职级过滤方法
   const filterPositionLevel = (value, row) => {
      return row.position_level_id === value;
   };

   onMounted(() => {
      init();
      getLevelList();
   });
</script>

<style scoped>
   /* 新增样式 */
   html,
   body,
   #app {
      height: 100%;
      margin: 0;
   }

   .container {
      height: 80vh;
      display: flex;
      flex-direction: column;
      padding: 20px;
      box-sizing: border-box;
      /* 包含padding在高度计算中 */
   }

   .full-height-row {
      flex: 1;
      min-height: 0;
      /* 修复flex容器滚动问题 */
   }

   .full-height-col {
      display: flex;
      flex-direction: column;
      height: 100%;
   }

   .full-height-card {
      flex: 1;
      display: flex;
      flex-direction: column;
   }

   .full-height-card :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 20px;
   }

   .full-height-tree {
      flex: 1;
      overflow: auto;
   }

   /* 保持原有其他样式 */
   .empty-tip {
      color: #999;
      text-align: center;
      padding: 40px 0;
   }

   .mb-4 {
      margin-bottom: 1rem;
   }

   .button-container {
      padding: 0 0px;
      display: flex;
      justify-content: space-between;
   }

   .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-right: 8px;
   }

   .operation-icons {
      display: none;
      margin-left: 10px;
   }

   .custom-tree-node .operation-icons {
      display: inline-flex;
      gap: 8px;
   }

   .custom-icon {
      font-size: 16px;
      color: #6860ff;
      cursor: pointer;
   }

   .custom-icon:hover {
      color: #6860ff;
   }

   :deep(.el-tree-node__content) {
      height: 32px;
   }

   :deep(.el-tree-node__content:hover) {
      background-color: #f5f7fa;
   }

   /* 搜索区域样式 */
   .search-area {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin-bottom: 20px;
      gap: 10px;
      background-color: #f5f7fa;
      padding: 15px;
      border-radius: 4px;
   }

   .search-item {
      display: flex;
      align-items: center;
      margin-right: 15px;
   }

   .search-item label {
      margin-right: 5px;
      white-space: nowrap;
   }

   /* 表格区域样式 */
   .table-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: 350px;
      width: auto;
      margin: 0 auto;
      text-align: center;
      border-radius: 4px;
      color: var(--el-color-primary);
      overflow: hidden;
   }

   /* 空数据提示样式 */
   .empty-data {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
   }

   /* 添加人员按钮区域 */
   .personnel-actions {
      margin: 10px 0;
      display: flex;
      justify-content: flex-end;
   }

   /* 表格标题样式 */
   .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      padding: 0 10px;
   }

   .table-title {
      font-size: 16px;
      font-weight: bold;
      color: var(--el-text-color-primary);
   }

   .table-count {
      font-size: 14px;
      color: var(--el-text-color-secondary);
   }
   .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
   }

   .disabled-node {
      color: #E64134;
      text-decoration: line-through;
   }

   .operation-icons {
      display: flex;
      align-items: center;
      gap: 8px;
   }

   .custom-icon {
      font-size: 16px;
      color: #409eff;
      cursor: pointer;

      &:hover {
         color: #66b1ff;
      }
   }
   :deep(.el-radio-button.is-active .el-radio-button__original-radio:not(:disabled) + .el-radio-button__inner) {
      background-color: #6b63ff !important;
      border-color: #e2e4fd;
   }
   :deep(.el-button--primary) {
      --el-button-bg-color: #6b63ff;
   }
   :deep(.el-pagination.is-background .el-pager li.is-active) {
      background-color: #1f1f1f;
   }
   :deep(.el-radio-button__inner:hover) {
      color: #6860ff;
   }
</style>
